/* eslint-disable no-param-reassign */
import { CloseOutlined, DeleteFilled, PlusOutlined } from '@ant-design/icons';
import { useModel } from '@umijs/max';
import {
  Alert,
  Button,
  Grid,
  Input,
  Popconfirm,
  Select,
  Slider,
  Tooltip,
  Upload,
  message,
} from 'antd';
import { DragDropContext, Draggable, Droppable } from 'react-beautiful-dnd';
import 'swiper/css';
import 'swiper/css/pagination';
import { Swiper, SwiperSlide } from 'swiper/react';
import { v4 as uuidv4 } from 'uuid';
import CardHover from '../CardHover';
import TagGroup from '../TagGroup';
import './index.less';

const { useBreakpoint } = Grid;

const getBase64 = (file) =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
const beforeUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('仅支持上传 JPG/PNG 文件!');
  }
  const isLt2M = file.size / 1024 / 1024 < 6;
  if (!isLt2M) {
    message.error('文件大小不得超过 6MB!');
  }
  return isJpgOrPng && isLt2M;
};
const Template = ({ arr }) => {
  const {
    initialState: { bgs },
    setInitialState,
  } = useModel('@@initialState');

  return (
    <div style={{ height: 'auto', overflow: 'hidden', padding: '6px 0' }}>
      <Swiper slidesPerView={'auto'} spaceBetween={8} className="mySwiper">
        {bgs.map((item, i) => {
          return (
            <SwiperSlide
              key={item}
              onClick={() => {
                setInitialState((s) => ({
                  ...s,
                  bgindex: item,
                }));
              }}
            >
              {item === 'video' ? (
                <CardHover>
                  <video
                    src="./demo.mp4"
                    autoPlay
                    controls={false}
                    muted
                    loop
                    className="fit"
                  ></video>
                </CardHover>
              ) : (
                <CardHover
                  closeable={item?.includes?.('base')}
                  onClose={() => {
                    setInitialState((s) => ({
                      ...s,
                      bgs: s.bgs.filter((it) => it !== item),
                    }));
                  }}
                >
                  <img
                    src={
                      item?.includes?.('base')
                        ? item
                        : require(`@/assets/p${item}.jpg`)
                    }
                    className="fit"
                  ></img>
                </CardHover>
              )}
            </SwiperSlide>
          );
        })}

        <SwiperSlide key={'diy'}>
          <Upload
            beforeUpload={beforeUpload}
            showUploadList={false}
            onChange={async ({ file }) => {
              const curbase64 = await getBase64(file.originFileObj);
              if (file.status === 'done') {
                setInitialState((s) => ({
                  ...s,
                  bgs: [...s.bgs, curbase64],
                }));
              }
            }}
          >
            <CardHover>
              <div
                className="flex column justify-center align-center gap-10"
                style={{
                  color: '#000',
                  backgroundColor: '#fff',
                  width: '100%',
                  height: '100%',
                }}
              >
                <PlusOutlined
                  style={{ fontSize: 16, fontWeight: 'lighter' }}
                ></PlusOutlined>
                <span style={{ fontSize: 12 }}>添加</span>
              </div>
            </CardHover>
          </Upload>
        </SwiperSlide>
      </Swiper>
    </div>
  );
};

function Actions({ setDrawer }) {
  const { lg } = useBreakpoint();

  const {
    initialState: { curData, userName, type },
    setInitialState,
  } = useModel('@@initialState');

  //更新数据
  const updatecurData = (newVal) => {
    setInitialState((s) => ({
      ...s,
      curData: newVal,
    }));
  };

  //拖拽结束
  function handleOnDragEnd(result) {
    if (!result.destination) return;
    const items = Array.from(curData);
    const [reorderedItem] = items.splice(result.source.index, 1);
    items.splice(result.destination.index, 0, reorderedItem);
    updatecurData(items);
  }

  //更新数据
  const updateData = (pid, id, key, newVal) => {
    setInitialState((s) => {
      const newData = [...s.curData].map((it) => {
        if (it.id === pid) {
          it = {
            ...it,
            list: [...it.list].map((item) => {
              if (item.id === id) {
                item = {
                  ...item,
                  [key]: newVal,
                };
              }
              return item;
            }),
          };
        }
        return it;
      });

      return {
        ...s,
        curData: newData,
      };
    });
  };

  //重置项目
  const resetList = (pid) => {
    const additem = {
      name: null,
      progress: 0,
      editting: true,
      id: uuidv4(),
    };
    setInitialState((s) => {
      const newData = [...s.curData].map((it) => {
        if (it.id === pid) {
          it = {
            ...it,
            list: [additem],
          };
        }
        return it;
      });

      return {
        ...s,
        curData: newData,
      };
    });
  };

  //删除项目
  const resetProject = (pid) => {
    setInitialState((s) => {
      const newData = [...s.curData].filter((it) => {
        return it.id !== pid;
      });
      return {
        ...s,
        curData: newData,
      };
    });
  };

  //删除本事项
  const deleteCur = (pid, id, fn) => {
    setInitialState((s) => {
      const newData = [...s.curData].map((it) => {
        if (it.id === pid) {
          it = {
            ...it,
            list: [...it.list].filter((item) => {
              return item.id !== id;
            }),
          };
        }
        return it;
      });
      return {
        ...s,
        curData: newData,
      };
    });
    setTimeout(() => {
      fn?.();
    }, 20);
  };

  //添加新事项
  const addCur = (pid, id, key, newVal) => {
    const additem = {
      name: null,
      progress: 0,
      editting: true,
      id: uuidv4(),
    };
    setInitialState((s) => {
      const newData = [...s.curData].map((it) => {
        if (it.id === pid) {
          let newlist = JSON.parse(
            JSON.stringify(
              it.list?.map((it) => ({
                ...it,
                editting: false,
              })),
            ),
          );
          const index = it.list.findIndex((cur) => cur.id === id);
          newlist.splice(index + 1, 0, additem);
          setTimeout(() => {
            const dom = document.getElementById(additem.id);
            dom?.scrollIntoView?.({ behavior: 'smooth', block: 'center' });
            dom?.focus?.();
          }, 50);
          it = {
            ...it,
            list: newlist,
          };
        }
        return it;
      });

      return {
        ...s,
        curData: newData,
      };
    });
  };

  return (
    <header className="App-header">
      <div
        className="flex gap-10"
        style={{
          padding: '12px 0',
          alignItems: 'center',
          overflow: 'visible',
        }}
      >
        <Input
          size="large"
          prefix={
            <img
              src={require('@/assets/yourname.jpeg')}
              style={{ width: 30, height: 30, marginLeft: -4, borderRadius: 6 }}
            />
          }
          placeholder="请输入你的名字"
          style={{ height: 42, backgroundColor: '#ffffff' }}
          variant="borderless"
          required={true}
          onChange={(e) => {
            const val = e.target.value;
            setInitialState((s) => ({
              ...s,
              userName: val,
            }));
          }}
          defaultValue={userName}
        ></Input>
        <Select
          style={{
            height: 42,
            borderRadius: 8,
            width: 120,
            backgroundColor: '#ffffff',
          }}
          variant="borderless"
          size="large"
          options={[
            {
              label: '日报',
              value: '1',
            },
            {
              label: '周报',
              value: '2',
            },
            {
              label: '月报',
              value: '3',
            },
            {
              label: '季报',
              value: '4',
            },
            {
              label: '年报',
              value: '5',
            },
          ]}
          value={type}
          onChange={(val) => {
            setInitialState((s) => ({
              ...s,
              type: val,
            }));
          }}
        ></Select>
        {!lg && (
          <Button
            size="large"
            type="text"
            style={{ flexShrink: 0,backgroundColor:"#ccc",color:"red" }}
            onClick={() => {
              setDrawer((s) => ({
                ...s,
                open: false,
              }));
            }}
          >
            ESC
          </Button>
        )}
      </div>
      <div style={{ height: 160 }}>
        <Template arr={[0, 1, 2, 3, 4, 5, 6, 7]}></Template>
      </div>

      <TagGroup></TagGroup>
      {!localStorage.getItem('BTIP') && curData?.length > 0 && (
        <Alert
          message="事项内按 Enter 键,继续添加新的事项"
          type="info"
          showIcon
          closable={{
            closeIcon: (
              <Button size="small" type="text">
                知道了
              </Button>
            ),
          }}
          onClose={() => {
            localStorage.setItem('BTIP', 'true');
          }}
          style={{ marginBottom: 12 }}
        />
      )}
      <DragDropContext onDragEnd={handleOnDragEnd}>
        <Droppable droppableId="curData">
          {(provided) => (
            <ul
              className="curData"
              {...provided.droppableProps}
              ref={provided.innerRef}
            >
              {curData.map(({ project, list, ...other }, index) => {
                return (
                  <Draggable
                    key={other.id}
                    draggableId={other.id}
                    index={index}
                  >
                    {(provided) => (
                      <li ref={provided.innerRef} {...provided.draggableProps}>
                        <div className="spread" {...provided.dragHandleProps}>
                          <div>{project}</div>
                          <div className="flex gap-10 hoverable">
                            <Popconfirm
                              title="是否清空下方事项?"
                              description="默认保留一个事项"
                              okText="是"
                              cancelText="否"
                              onConfirm={() => {
                                resetList(other.id);
                              }}
                              placement="bottomRight"
                              getPopupContainer={() => false}
                              trigger={'hover'}
                            >
                              <Button
                                type="text"
                                danger
                                icon={<DeleteFilled />}
                                size="middle"
                              ></Button>
                            </Popconfirm>
                            <Popconfirm
                              title="是否移除该项?"
                              description="移除后下方事项将会一并移除"
                              okText="是"
                              cancelText="否"
                              onConfirm={() => {
                                resetProject(other.id);
                              }}
                              placement="bottomRight"
                              getPopupContainer={() => false}
                              trigger={'hover'}
                            >
                              <Button
                                icon={
                                  <CloseOutlined style={{ fontSize: 14 }} />
                                }
                                type="text"
                                size="middle"
                              ></Button>
                            </Popconfirm>
                          </div>
                        </div>

                        <div>
                          {list?.map(
                            ({ id, name, editting, progress }, index) => {
                              let isfirst = index === 0;

                              return (
                                <div
                                  key={id}
                                  className="flex-1 flex column gap-10"
                                  style={{ marginBottom: 18 }}
                                >
                                  <div className="flex gap-10">
                                    <div className="tager">{index + 1}</div>
                                    <Input
                                      id={id}
                                      placeholder="填写事项,按 Delete 键删除本事项"
                                      suffix={
                                        <div
                                          className="flex"
                                          style={{
                                            gap: 4,
                                            marginRight: -6,
                                            cursor: 'pointer',
                                          }}
                                        >
                                          <Tooltip
                                            title="按键盘 Del 键删除本事项"
                                            placement="bottomRight"
                                          >
                                            <span
                                              className="kbd"
                                              style={{
                                                display: isfirst
                                                  ? 'none'
                                                  : 'flex',
                                              }}
                                              onClick={() => {
                                                deleteCur(other.id, id, () => {
                                                  const prev =
                                                    list[index - 1] ?? null;
                                                  if (!prev) return;
                                                  const dom =
                                                    document.getElementById(
                                                      prev.id,
                                                    );
                                                  dom?.scrollIntoView?.({
                                                    behavior: 'smooth',
                                                    block: 'center',
                                                  });
                                                  dom?.focus?.();
                                                });
                                              }}
                                            >
                                              Del
                                            </span>
                                          </Tooltip>
                                          <Tooltip
                                            title="按键盘 Enter 键添加新事项"
                                            placement="bottomRight"
                                          >
                                            <span
                                              className="kbd"
                                              onClick={() => {
                                                addCur(other.id, id);
                                              }}
                                            >
                                              Enter
                                            </span>
                                          </Tooltip>
                                        </div>
                                      }
                                      allowClear
                                      defaultValue={name}
                                      onChange={(e) => {
                                        updateData(
                                          other.id,
                                          id,
                                          'name',
                                          e.target.value,
                                        );
                                      }}
                                      style={{
                                        flex: 1,
                                        borderRadius: 10,
                                        boxShadow: editting
                                          ? '0 0 6px #91CAFF'
                                          : 'none',
                                      }}
                                      onFocus={() => {
                                        updateData(
                                          other.id,
                                          id,
                                          'editting',
                                          true,
                                        );
                                      }}
                                      onBlur={() => {
                                        updateData(
                                          other.id,
                                          id,
                                          'editting',
                                          false,
                                        );
                                      }}
                                      onKeyDown={(e) => {
                                        if (e.key === 'Delete') {
                                          if (isfirst) return;
                                          deleteCur(other.id, id, () => {
                                            const prev =
                                              list[index - 1] ?? null;
                                            if (!prev) return;
                                            const dom = document.getElementById(
                                              prev.id,
                                            );
                                            dom?.scrollIntoView?.({
                                              behavior: 'smooth',
                                              block: 'center',
                                            });
                                            dom?.focus?.();
                                          });
                                        }
                                      }}
                                      onPressEnter={(e) => {
                                        addCur(other.id, id);
                                      }}
                                    ></Input>
                                  </div>
                                  <div style={{ padding: '0 4px 0 10px' }}>
                                    <Slider
                                      value={progress}
                                      step={10}
                                      style={{ margin: 0 }}
                                      onChange={(value) => {
                                        updateData(
                                          other.id,
                                          id,
                                          'progress',
                                          value,
                                        );
                                      }}
                                    ></Slider>
                                  </div>
                                </div>
                              );
                            },
                          )}
                        </div>
                      </li>
                    )}
                  </Draggable>
                );
              })}
              {provided.placeholder}
            </ul>
          )}
        </Droppable>
      </DragDropContext>
    </header>
  );
}

export default Actions;
